package cn.hairui.blog.controller;

import cn.hairui.blog.constant.PubConstant;
import cn.hairui.blog.model.User;
import cn.hairui.blog.model.WebInfo;
import cn.hairui.blog.service.UserService;
import cn.hairui.blog.service.WebInfoService;
import cn.hairui.blog.util.MD5;
import com.alibaba.druid.support.json.JSONUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

/**
 * @author lihairui
 * @version V1.0
 * @date: 2019/8/3 17:38
 */
@Controller
public class UserController {

    @Autowired
    private WebInfoService webInfoService;
    @Autowired
    private UserService userService;

    @RequestMapping(value = "login")
    public String login(HttpServletRequest request, Model model) {
        WebInfo webInfo = webInfoService.find(PubConstant.MY_INFO_ID);
        model.addAttribute("webinfo", webInfo);
        return "login";
    }

    @RequestMapping(value = "forget")
    public String forget(HttpServletRequest request, Model model) {
        WebInfo webInfo = webInfoService.find(PubConstant.MY_INFO_ID);
        model.addAttribute("webinfo", webInfo);
        return "forget";
    }


    @RequestMapping(value = "userlogin", method = RequestMethod.POST)
    @ResponseBody
    public String userlogin(User user, HttpServletRequest request) {
        HttpSession session = request.getSession();
        Map map = new HashMap();
        String password = MD5.getMD5ofStr(user.getPassword());
        User domain = userService.findByUsernameAndPwd(user.getUsername(), password);
        if (domain != null && PubConstant.YES_NO_N.equals(domain.getLockflag())) {
            session.setAttribute(PubConstant.GLOBAL_SESSION_NAME, domain);
            map.put(PubConstant.flag, PubConstant.success);
            return JSONUtils.toJSONString(map);
        } else if (domain != null && !PubConstant.YES_NO_N.equals(domain.getLockflag())) {
            //登录失败的情况下销毁以前的session信息
            session.invalidate();
            map.put(PubConstant.flag, PubConstant.locked);
            return JSONUtils.toJSONString(map);
        } else {
            //登录失败的情况下销毁以前的session信息
            session.invalidate();
            map.put(PubConstant.flag, PubConstant.failed);
            return JSONUtils.toJSONString(map);
        }
    }
}
